var express = require('express');
var router = express.Router();
var user = require("../model/user").getModel('user');
var u = require("../util/util");
var querystring = require("querystring");
/* GET users listing. */
router.get('/', function (req, res, next) {
    res.send('respond with a resource');
});
router.get("/auth", function (req, res) {
    var {userid} = req.query;
    user.findOne({
        _id: userid
    }, function (err, doc) {
        if (!!err) {
            return u.errlog(err, res);
        }
        if (!!doc) {
            return res.json({
                code: 0,
                result: {
                    doc
                }
            })
        }
    })
});
router.get("/login", function (req, res) {
    var {username, password} = req.query;
    console.log(`username ------> `,username)
    console.log(`password ------> `,password)
    user.findOne({
        username,
        password
    }, function (err, doc) {
        if (!!err) {
            return u.errlog(err, res);
        }

        if (!!doc) {
            res.cookie('userid', querystring.escape(doc._id));
            return res.json({
                code: 0,
                result: {
                    doc
                }
            })
        }
        else {
            return u.msglog(res, '没有此用户');
        }
    })
})
router.post("/register", function (req, res, next) {
    var {username, email, password, sex, birthDay} = req.body;
    user.findOne({
        username
    }, function (err, doc) {
        if (err) {
            return u.errlog(err, res);//要用return,不然会报错
        }
        //用户名重复
        if (doc) {
            return u.msglog(res, '用户名重复');
        }
        else {
            new user({username, email, password, sex, birthDay}).save(function (err, doc) {
                if (err) {
                    return u.errlog(err, res);
                }
                else {
                    return res.json(
                        {
                            code: 0,
                            result: {
                                username: doc.username,
                                email: doc.email,
                                password: doc.password,
                                sex: doc.sex,
                                birthDay: doc.birthDay,
                                createTime: doc.createTime,
                                userId: doc._id
                            }
                        })
                }
            })
        }
    })
});
module.exports = router;
